package cn.snorlaxzjt.LBSserver.push;

import cn.snorlaxzjt.LBSserver.service.ApnsService;
import cn.snorlaxzjt.LBSserver.service.CIMSessionService;
import cn.snorlaxzjt.LBSserver.service.MessageService;

import cn.snorlaxzjt.LBSserver.service.UserService;
import com.farsunset.cim.sdk.server.model.CIMSession;
import com.farsunset.cim.sdk.server.model.Message;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.Objects;

@Component
public class CimMessagePusher {
    @Autowired
    MessageService messageService;
    @Value("${server.host}")
    private String host;
    @Resource
    private CIMSessionService cimSessionService;
    @Resource
    private ApnsService apnsService;

    @Resource
    private UserService userService;


    /*
     * 向用户发送消息
     *
     * @param message
     */
    public void push(Message message) {
        message.setSender(String.valueOf(userService.getCurrentUserId()));
        CIMSession session = cimSessionService.get(message.getReceiver());

        if (session == null) {
            messageService.addMessage(message, 0);
            return;
        }


        if (session.isConnected() && Objects.equals(host, session.getHost())) {
            session.write(message);
            messageService.addMessage(message, 1);
        }


    }
}
